package user.main;

import java.util.ArrayList;

/**
 * This class keeps track of several running threads. This is especially useful for when multiple files are 
 * being written by several threads; it simply and easily allows the user to see whether the threads are still 
 * running.
 * 
 * The first step is adding threads using the addThread method (optionally, a string could be included that 
 * will be printed to the console when the thread dies). Then, the run() method should be called. The threads 
 * will be tracked; when each one dies, an exit string (either the provided one or a generated one) is printed 
 * to the console. When all threads are done executing, the string "Done!" is printed.
 * 
 * Also, TrackerThread implements Thread, so use that API.
 * 
 * @author Trevor Terris
 *
 */
public class TrackerThread extends Thread
{
	private ArrayList<Thread> myThreads = new ArrayList<Thread>();
	private ArrayList<String> myExitStrings = new ArrayList<String>();
	private ArrayList<Boolean> myHasWritten = new ArrayList<Boolean>();
	/**
	 * This method adds a running thread to the list of threads. The first argument is the thread itself, and 
	 * the second argument is the string that should be written to the console when the thread dies.
	 * 
	 * @param t
	 * @param e
	 */
	public void addThread(Thread t, String e)
	{
		myExitStrings.add(e);
		myThreads.add(t);
		myHasWritten.add(false);
	}
	/**
	 * This method adds a running thread to a list of threads. The argument is the thread that should be added.
	 * 
	 * @param t
	 */
	public void addThread(Thread t)
	{
		addThread(t, "Done with process " + myThreads.size() + ".");
	}
	/**
	 * After all threads have been added, call this method. It will print a string after the death of each 
	 * thread, and the string "Done!" when all threads have died.
	 */
	public void run()
	{

    	int numWritten = 0;

    	do
    	{
    		for (int i = 0; i < myThreads.size(); i++)
    		{
    			while (i < myThreads.size() && !myHasWritten.get(i) && !myThreads.get(i).isAlive())
    			{
    				System.out.println(myExitStrings.get(i));
    				myHasWritten.set(i, true);
    				numWritten++;
    				i++;
    			}
    			if (numWritten < myThreads.size())
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						System.out.println("Interrupted!");
					}
    		}
    	} while (numWritten < myThreads.size());
		
		System.out.println("Done.");
	}
}
